
# 算术平方根
import cmath # math 数学运算 cmath 复杂数学运算
# num = float(input("Input a number:"))
num = -255
print("**0.5:", num**0.5) # 0和正数
print("sqrt:", cmath.sqrt(num)) # 实数和复数
print()

# 一元二次方程ax**2 + bx + c = 0
import cmath
# a = float(input("Input 'a':"))
# b = float(input("Input 'b':"))
# c = float(input("Input 'c':"))
a, b, c = 1, 5, 6
d = (b**2) - (4*a*c)
sf = (-b-cmath.sqrt(d))/(2*a)
ss = (-b+cmath.sqrt(d))/(2*a)
if ss != sf:
	print("solution:", sf, ss)
else:
	print("solution:", sf)
print()

# 三角形三边长度求面积
# a = float(input("Input 'a':"))
# b = float(input("Input 'b':"))
# c = float(input("Input 'c':"))
a, b, c = 5, 6, 7
s = (a+b+c)/2
area = (s*(s-a)*(s-b)*(s-c))**0.5   # 海伦公式
print("area:", area)
print()

# 随机数生成
import random
print(random.randint(0, 9))
print(random.random())
print(random.randrange(0, 100, 2))
print()

# 判断字符串是否为数字
# str.isdigit() 方法检测字符串是否只由数字组成。
# str.isnumeric() 方法检测字符串是否只由数字组成, 但只针对unicode对象。
def is_number(s):
	try:
		float(s)
		print("f:", s, float(s), end = ' ')
		return True
	except ValueError:
		pass

	try:
		import unicodedata
		unicodedata.numeric(s)
		print("u:", s, unicodedata.numeric(s), end = ' ')
		return True
	except (TypeError, ValueError):
		pass

	return False

print(is_number('foo'))   # False
print(is_number('1'))     # True
print(is_number('1.3'))   # True
print(is_number('-1.37')) # True
print(is_number('1e3'))   # True
# 测试 Unicode
print(is_number('٥'))   # 阿拉伯语 5  True
print(is_number('๒'))   # 泰语 2      True
print(is_number('四'))   # 中文数字    True
print(is_number('©'))   # 版权号       True
print()

# 判断闰年
# 整百年能被400整除的是闰年， 非整百年能被4整除的为闰年。
# year = int(input("Input the year:"))
year = 2012
print(year, "is", end = ' ')
if ((year % 4) == 0) and ((year % 100) != 0) or ((year % 400) == 0):
	print('leap year')
else:
	print('not a leap year')
print()

# 质数(素数)判断
# num = int(input("Input the number:"))
num = 12321
if num < 2:
	print(num, "is not a prime number")
else:
	for i in range(2, num):
		if (num % i) == 0:
			print(num, "is not a prime number")
			print(i, "*", num//i, "=", num)
			break
	else:
		print(num, "is a prime number")
print()

# 九九乘法表
for i in range(1, 10):
	for j in range(1, i+1):
		print("{}*{}={}".format(j, i, j*i), end = '\t')
	else:
		print()
print()

# 斐波那契数列
# 第0项是0，第1项是第一个1。从第三项开始，每一项都等于前两项之和。
# num = int(input("Input the number:"))
num = 18
a, b = 0, 1
for i in range(0, num):
	print(a, end = ' ')
	a, b = b, a+b
print('\n')

# 阿姆斯特朗数
# 一个n位正整数等于其各位数字的n次方之和。
# num = int(input("Input the number:"))
num = 407
ns = str(num)
nl = len(ns)
sum = 0
for i in range(0, nl):
	sum += int(ns[i])**nl
# print("sum:", sum)
if num == sum:
	print(num, "is an Armstrong number!")
else:
	print(num, "is not an Armstrong number!")
# 获取指定区间内的阿姆斯特朗数
# lower, upper = 0, 0
# while lower < 1:
#	lower = int(input("Input the lower(>0):"))
# while upper < 1:
#	upper = int(input("Input the upper(>lower):"))
lower, upper = 1, 10000
for num in range(lower, upper):
	ns = str(num)
	nl = len(ns)
	sum = 0
	for i in range(0, nl):
		sum += int(ns[i])**nl
	# print("sum:", sum)
	if num == sum:
		print(num, end=' ')
print('\n')

# 进制转换
# dec = int(input("Input a number:"))
dec = 8888
print("dec:", dec, "bin:", bin(dec), "oct:", oct(dec), "hex:", hex(dec))
print()

# ascii码与字符相互转换
# c = input("Input a character: ")
# a = int(input("Input an ascii code:"))
c = 'a'
a = 48
print("[character] {}\t->  {} [ascii dec]\t{} [ascii hex]".format(c, ord(c), hex(ord(c))))
print("[ascii dec] {}\t->  {} [character]\t{} [ascii hex]".format(a, chr(a), hex(a)))
print()

# 最大公约数
def gcd(a, b):
	if b > a:
		a, b = b, a		# b为最小值
	if a % b == 0:
		return b		# 判断b是否为最大公约数
	for i in range(b//2+1, 1, -1):	# 倒序求最大公约数更合理
		if b % i == 0 and a % i == 0:
			return i
	return 0
# while(True):
# 	a = int(input("Input 'a':"))
# 	b = int(input("Input 'b':"))
# 	print(gcd(a, b))

# 最小公倍数
def lcm(a, b):
	if b > a:
		a, b = b, a		# a为最大值
	if a % b == 0:
		return a		# 判断a是否为最小公倍数
	mul = 2				# 最小公倍数为最大值的倍数
	while a*mul % b != 0:
		mul += 1
	return a*mul
# while(True):
# 	a = int(input("Input 'a':"))
# 	b = int(input("Input 'b':"))
# 	print(lcm(a, b))

# 生成日历
import calendar
from datetime import date
now = date.today()
tnow = date.timetuple(now)
print(calendar.month(tnow[0], tnow[1]))

# 字符串大小写转换
str = "This is my house!"
print("upper:", str.upper())
print("lower:", str.lower())
print("capitalize:", str.capitalize())
print("title:", str.title())
print()

# 计算每个月的天数
import calendar
print(calendar.mdays[9], end=' ')
monthRange = calendar.monthrange(2016, 9)
print("first day:", monthRange[0]+1, "total days:", monthRange[1])
print()

# 获取昨天日期
import datetime
today = datetime.date.today()
oneday = datetime.timedelta(days=1)
yesterday = today - oneday
print("yesterday:", yesterday, '\n')

# list常用操作
li = ["a", "b", "mpilgrim", "z", "example"]
print("origin:", li)
# list 增加元素 (返回none)
li.append("new")
print("append:", li)
li.insert(2, "222")
print("insert:", li)
li.extend(["two", "elements"])
print("extend:", li)
# list 搜索
print(li.index("example"), li.index("new"), "c" in li)
# list 删除元素
li.remove("z")
li.remove("new")
print("remove:", li)
p = li.pop()
print("pop:", p, li)
print()
# list 运算符
li = li + ["example", "new"]
print("+: ", li)
li += ["two"]
print("+=:", li)
li = li * 2
print("*: ", li)
print()
# join 连接 list 成 字符串
# 连接一个存在一个或多个非字符串元素的 list 将引发一个异常。
params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
paramsL = ["%s=%s" % (k, v) for k, v in params.items()]
print("list:", paramsL)
paramsS = ";".join(paramsL)
print("string:", paramsS)
# list 分割字符串
print("split(\";\"):", paramsS.split(";"))
print("split(\";\", 2):", paramsS.split(";", 2)) # 分割次数
print()
# list 过滤
print(li)
fL = [elem for elem in li if len(elem) < 3]
print(fL, '\n')
